package cn.itcast.eduservice.listener;

import cn.itcast.baseservice.exceptionhandle.GuliException;
import cn.itcast.eduservice.entity.EduSubject;
import cn.itcast.eduservice.entity.excel.SubjectData;
import cn.itcast.eduservice.service.EduSubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    // 因为SubjectExcelListener不能交给Spring进行管理，需要自己new，不能注入其它对象
    // 不能实现数据库操作,需要在 new SubjectExcelListener 这个的时候，通过有参的构造接收到

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(){}


    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    // 判断一级分类是否存在
    private EduSubject existOneSubject(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");

        EduSubject oneSubject = eduSubjectService.getOne(wrapper);

        return oneSubject;
    }

    // 判断二级分类是否存在
    private EduSubject existTwoSubject(String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);

        EduSubject twoSubject = eduSubjectService.getOne(wrapper);

        return twoSubject;
    }

    /**
     * 读取excel的内容，一行一行的读
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw  new GuliException(20001,"Excel中没有内容");
        }

        // 添加一级分类
        EduSubject oneSubject = this.existOneSubject(subjectData.getOneSubjectName());
        if (oneSubject == null) { // 一级分类不存在
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName()); // 一级分类名称

            eduSubjectService.save(oneSubject);
        }

        // 添加二级分类
        // 获取一级分类的id
        String pid = oneSubject.getId();
        EduSubject twoSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), pid);
        if (twoSubject == null) { // 二级分类不存在
            twoSubject = new EduSubject();
            twoSubject.setTitle(subjectData.getTwoSubjectName()); // 二级分类名称
            twoSubject.setParentId(pid);

            eduSubjectService.save(twoSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
